package com.base.system.base.db.specifications;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

public class FindInSetSpecification<T> extends AbstractSpecification<T> {
    private static final long serialVersionUID = 6690291922287079277L;
    private final String property;
    private final Object[] patterns;

    public FindInSetSpecification(String property, JoinType joinType, Object... v) {
        this.property = property;
        patterns = v;
        this.joinType = joinType;
    }

    @Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
        From from = getFrom(property, root);
        String attr = getProperty(property);
        List<Predicate> predicates = new ArrayList<>(patterns.length);
        for (int i = 0; i < patterns.length; i++) {
            Expression<Integer> find_in_set = cb.function("FIND_IN_SET", Integer.class, cb.literal(patterns[i]), from.get(attr));
            predicates.add(cb.gt(find_in_set, 0));
        }
        return cb.or(predicates.toArray(new Predicate[patterns.length]));
    }
}
